<template>
    <el-table
        ref="tableRef"
        :data="tableData"
        v-bind="tableDefaultAttribute"
        row-key="id"
        :max-height="tableHeight"
        table-layout="auto"
        @cell-dblclick="update"
        @sort-change="handleSortChange"
    >
        <template #empty>
            <span>无数据</span>
        </template>
        <el-table-column type="selection" width="55" :align="'center'" />
        <template v-for="col in tableColumns" :key="col.prop">
            <el-table-column
                v-if="!col.isHidden"
                :align="col.align"
                :prop="col.prop"
                :label="col.label"
                :type="col.type"
                :formatter="col.formatter"
                :sortable="col.sortable"
            >
                <template
                    v-if="col.formFieldItemType === 'boolean'"
                    #default="scope"
                >
                    <el-switch
                        v-model="scope.row[`${col.prop}`]"
                        :active-value="'Y'"
                        :inactive-value="'N'"
                    />
                </template>
            </el-table-column>
        </template>
    </el-table>
    <el-button-group class="bg">
        <el-button class="btn" type="primary"  @click="add"
            >增加</el-button
        >
        <el-button class="btn" type="primary"  @click="onDelete"
            >删除</el-button
        >
        <el-button class="btn" type="primary"  @click="onQuery"
            >查询</el-button
        >
    </el-button-group>
    <div class="page">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[50, 100, 150, 200]"
            layout="sizes, prev, pager, next"
            :total="totalnum"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
    </div>
    <el-dialog
        v-model="dialogUpdateVisible"
        title="箱区维护"
        draggable
        destroy-on-close
        :center="true"
    >
        <NormalSysForm
            :formOptions="formOptions"
            :formItems="formItems"
            :formData="paramData"
            :createActionName="createActionName"
            :updateActionName="updateActionName"
            :rules="rules"
            @create="onAdded"
            @update="onUpdated"
            @close="onCloseDialog"
        >
        </NormalSysForm>
    </el-dialog>
    <el-dialog
        v-model="dialogQueryVisible"
        title="箱区查询"
        draggable
        destroy-on-close
    >
        <QueryForm
            :queryItems="queryItems"
            @yh-closedialog="onCloseDialog"
        ></QueryForm>
    </el-dialog>
</template>
<script setup lang="ts" name="CyCfsArea">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox, ElTable, FormRules } from 'element-plus';
// import { Delete, Plus, Search } from '@element-plus/icons-vue';
import {
    isEmpty,
    forEach,
    forEachRight,
    includes,
    findIndex,
    omit,
} from 'lodash';
import NormalSysForm from '@/components/forms/NormalSysForm.vue';
import { useAppStore } from '@/store/app';
import { transFormatter } from '@/common/tools';
const { cyCfs } = useAppStore();
import type { CyCfsAreaModel } from '@/common/types/basedataModel';
import {
    tableDefaultAttribute,
    useTableInfo,
    useTableHeightInfo,
    tableColumnDefault,
} from '@/hooks/useTable';
import type { FormFieldItem, QueryItem, TableColumn } from '@/common/types/app';
import { Request } from '@/app/request';
import {
    initObjectProperty,
    pickFormFromTable,
    pickQueryFromTable,
} from '@/common/tools';
const tableRef = ref<InstanceType<typeof ElTable>>();
const tableData = ref<Array<CyCfsAreaModel>>([]);
const paramData = reactive<CyCfsAreaModel>({});
const tableHeight = ref(100);
const formOptions = reactive<{}>({});

// TODO:: 未完成
const rules = reactive<FormRules>({
    cfs_cod: [{ required: true, message: '请输入站点', trigger: 'blur' }],
    cy_area: [
        { required: true, message: '请输入箱区', trigger: 'blur' },
        { max: 4, message: '箱区不能超是4位', trigger: 'blur' },
    ],
});
const onFormatter = (_row: any, column: any, cellValue: any) => {
    let data: { value: string | number; label: string }[];
    if (column['property'] === 'cfs_cod') {
        data = cyCfs;
    } else {
        return cellValue;
    }

    return transFormatter(cellValue, data);
};
const tableColumns = reactive<TableColumn[]>([
    {
        ...tableColumnDefault,
        order: 1,
        prop: 'cfs_cod',
        label: '站点',
        sortable: 'custom',
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: cyCfs,
    },
    {
        ...tableColumnDefault,
        order: 2,
        prop: 'cy_area',
        label: '箱区',
        sortable: 'custom',
        formFieldItemType: 'input',
    },
    {
        ...tableColumnDefault,
        order: 3,
        prop: 'remark',
        label: '备注',
        sortable: 'custom',
    },
]);

const formItems = reactive<Array<FormFieldItem>>(
    pickFormFromTable(tableColumns),
);

const createActionName = ref('箱区增加');
const updateActionName = ref('箱区修改');

//const tableHeight = ref(0);

const dialogQueryVisible = ref(false);
const dialogUpdateVisible = ref(false);
let queryWhere = {};

// let tableHeight: ComputedRef;

const onRefresh = async () => {
    const req = new Request('箱区查询', {
        skip: (currentPage.value - 1) * pageSize.value,
        take: pageSize.value,
        order: orders,
        ...queryWhere,
    });
    const r = await req.post();

    totalnum.value = r.ext;
    tableData.value.length = 0;
    if (!isEmpty(r.obj)) {
        tableData.value = r.obj;
    }
};
const {
    currentPage,
    orders,
    pageSize,
    totalnum,
    handleSizeChange,
    handleCurrentChange,
    handleSortChange,
} = useTableInfo(onRefresh);
onMounted(() => {
    onRefresh();
    useTableHeightInfo(tableRef, tableHeight);
});

const add = () => {
    initObjectProperty(paramData);
    dialogUpdateVisible.value = true;
};
const update = (row: any) => {
    Object.assign(paramData, row, { primary_cod: {
        cfs_cod: row['cfs_cod'],
        cy_area: row['cy_area']
    } });
    dialogUpdateVisible.value = true;
};
const onAdded = (data: CyCfsAreaModel) => {
    tableData.value.unshift(data);
};
const onUpdated = (data: CyCfsAreaModel) => {
    const i = findIndex(tableData.value, (o: CyCfsAreaModel) => {
        return (o.cfs_cod === data.primary_cod.cfs_cod && o.cy_area === data.primary_cod.cy_area);
    });
    if (i > -1) {
        Object.assign(tableData.value[i], omit(data, ['primary_cod']));
    } else {
        ElMessage.error('修改失败');
    }
};
const onCloseDialog = async (arg?: any) => {
    if (dialogUpdateVisible.value) {
        dialogUpdateVisible.value = false;
    }
    if (dialogQueryVisible.value) {
        // 查询
        currentPage.value = 1;
        queryWhere = arg;
        onRefresh();

        dialogQueryVisible.value = false;
    }
};

const onDelete = async () => {
    const rows: Array<CyCfsAreaModel> = tableRef.value?.getSelectionRows() || [];
    if (rows.length === 0) {
        ElMessage.info({
            message: '请选择要删除数据',
        });
        return;
    }
    const ids = Array<number>();
    const cfs = Array<string>();
    forEach(rows, (v: CyCfsAreaModel) => {
        ids.push(v.id!);
        cfs.push(v.cfs_area!);
    });

    const msg = cfs.join(',     ');
    // const delids = ids.join(',');
    const cr = await ElMessageBox.confirm(msg, '确认删除如下箱区', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            return true;
        })
        .catch(() => {
            return false;
        });
    if (cr) {
        //
        const req = new Request('箱区删除', { ids });
        const r = await req.post();
        if (r.code > 100) {
            forEachRight(tableData.value, (v: CyCfsAreaModel, i: number) => {
                if (includes(ids, v.id)) {
                    tableData.value.splice(i, 1);
                }
            });
        }
    }
};

const onQuery = () => {
    dialogQueryVisible.value = true;
};
const queryItems: Array<QueryItem> = pickQueryFromTable(tableColumns);
</script>
<style lang="scss" scoped>
.bg {
    margin-top: 10px;

    .btn {
        margin-right: 10px;
    }
}

.page {
    float: right;
    margin-top: 10px;
}
</style>
